const express=require('express')
const router=express.Router()
const pool=require('../pool')
const query=require('./utils')
const {host} = require('./host')
const multer=require('multer')
const bodyparser=require('body-parser')

// 获取广场评论
router.get('/',async (req,res)=>{
    let page=req.query.page
    let openId=req.query.openId
    let count=8
    let start=(parseInt(page)-1)*count
    let sql,key
    if(!openId){
        sql=`SELECT j.id,j.open_id,j.photo,j.comment,u.nickName,u.sex,u.open_id,u.avatar FROM jipu as j INNER JOIN  userinfo as u on j.open_id=u.open_id ORDER BY j.id DESC limit ${start},${count};`
        key=[]
        let ret=await query(sql,key);
        // console.log(sql,ret);
        sql = `select count(id) as count from jipu `;
        let total=await query(sql)
        res.send({comments:ret,total})
    }else{
        sql=`SELECT j.id,j.open_id,j.photo,j.comment,u.nickName,u.sex,u.open_id,u.avatar FROM jipu as j INNER JOIN  userinfo as u on j.open_id=u.open_id where j.open_id=? ORDER BY j.id DESC limit ${start},${count};`
        key=[openId]
        let ret=await query(sql,key)
        sql = `select count(id) as count from jipu where open_id= ?  `;
        let total=await query(sql,key)
        res.send({comments:ret,total})
    }
})
// 修改磁盘存储规则
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, 'image/comment/')
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname)
    }
})
var upload2 = multer({ storage: storage })
// 上传图片
router.post('/upload',upload2.single('file'),async (req,res)=>{
    let imgFile= req.file.path.replace(/\\/g, '/').slice(6);
    res.send({
        code:0,
        data:{
            path:host+'/'+imgFile,
            relative_path:imgFile
        }
    })
})
// 上传数据插入数据库
router.post('/uploadData',async (req,res)=>{
    let data=req.body
    let sql='INSERT INTO jipu ( photo,comment,open_id ) VALUES (?,?,?); '
    let ret=await query(sql,Object.values(data))
    if(ret.affectedRows>0){
        res.send({
            code:0,
            msg:'success',
            
        })
    }
})
// 删除评论
router.get('/delete',async (req,res)=>{
    let list=req.query.list
    let sql=`DELETE  from jipu where id in (${list})`
    let ret =await query(sql)
    res.send({code:0,msg:'success'})
})
module.exports=router